package com.wh.minihelp.flower.service;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;

import org.apache.commons.lang.StringUtils;

import com.wh.db.Page;
import com.wh.db.sql.SQLUtils;
import com.wh.json.JSONUtil;
import com.wh.minihelp.filter.IFunctionContext;
import com.wh.minihelp.filter.IFunctionService;
import com.wh.minihelp.flower.dao.FlowerDao;
import com.wh.minihelp.flower.domain.ChildFlower;
import com.wh.minihelp.flower.domain.FamilyFlower;
import com.wh.minihelp.flower.domain.SysFlower;
import com.wh.minihelp.user.dao.UserDao;
import com.wh.minihelp.user.domain.ChildInfo;
import com.wh.minihelp.user.domain.FamilyAccount;
import com.wh.minihelp.user.service.UserService;
import com.wh.minihelp.user.util.UserUtil;
import com.wh.web.util.lang.StringUtil;

/**
 * 小红花过滤器
 * 
 * @author washheart@163.com
 */
public class FlowerService implements IFunctionService {

	// private static final Object MD_Login = "L";
	public static final String MD_ADD = "add", // 添加红花
			MD_DEL = "del", // 删除红花
			MD_ORDER = "order", // 上移/下移
			MD_Add_ChildFlower = "ACF", // 添加一条关于消耗的红花记录
			MD_Add_NEWS = "news", // 显示最新的红花信息
			MD_Detail = "detail";// 查看某小孩的红花明细
	public static final String Module = "f";
	public static final String KEY_Cur_Child = "FlowerService.cur_child";
	private IFunctionContext ctx;
	private FlowerDao dao;
	private FamilyAccount curFa;

	public void dispather(IFunctionContext fctx, String method) throws ServletException, IOException {
		this.ctx = fctx;
		this.dao = ctx.getDao(FlowerDao.class);
		this.curFa = UserUtil.getUser(fctx);
		if (this.curFa == null) {
			gotoOverview();
			return;
		}
		if (MD_Add_NEWS.equals(method)) {
			showNewsFlowers();
		} else if (MD_Detail.equals(method)) {// 查看某小孩的红花明细
			if (UserUtil.isFamilyMember(fctx, curFa, true)) gotoFlowerDetail();
		} else if (UserUtil.isFamilyManager(fctx, curFa, true)) {
			if (MD_Add_ChildFlower.equals(method)) {
				addChildFlower();// 添加某个小孩的红花记录
			} else if (MD_ADD.equals(method)) {
				jsonAdd();
			} else if (MD_DEL.equals(method)) {
				jsonDel();
			} else if (MD_ORDER.equals(method)) {
				jsonChangeOrder();
			}
		}
	}

	private void addChildFlower() throws IOException {
		String childId = ctx.getParameter("childId");// 获取红花名称
		if (StringUtils.isEmpty(childId)) {
			ctx.json(JSONUtil.toJsonMsg(false, "请选择要添加红花的小孩！"));
			return;
		}
		String flowerName = ctx.getParameter("flowerName");// 获取红花名称
		if (StringUtils.isEmpty(flowerName)) {
			ctx.json(JSONUtil.toJsonMsg(false, "请输入一个有效的红花名称！"));
			return;
		}
		int flowerNumber = 0;
		try {
			flowerNumber = Integer.parseInt(ctx.getParameter("flowerNumber"));
		} catch (Throwable e) {
			ctx.json(JSONUtil.toJsonMsg(false, "请输入红花增减数量！"));
			return;
		}
		if (flowerNumber <= 0) {
			ctx.json(JSONUtil.toJsonMsg(false, "红花增减数量应该大于0！"));
			return;
		}
		int oper = SysFlower.ADD;
		try {
			oper = Integer.parseInt(ctx.getParameter("oper"));
			if (oper == SysFlower.ADD) {//
			} else if (oper == SysFlower.SUB) {
				flowerNumber = -1 * flowerNumber;
			} else {
				ctx.json(JSONUtil.toJsonMsg(false, "请设置红花增减类别！"));
				return;
			}
		} catch (Throwable e) {}
		String flowerDesc = ctx.getParameter("flowerDesc");// 获取本次增加的描述新信息
		if (StringUtils.isEmpty(flowerDesc)) {
			ctx.json(JSONUtil.toJsonMsg(false, "请输入增减红花时的描述信息！"));
			return;
		}
		ChildFlower cf = new ChildFlower();
		cf.setFlowerDate(new Date());
		cf.setFlowerDesc(flowerDesc);
		cf.setFlowerName(flowerName);
		cf.setFlowerNumber(flowerNumber);
		cf.setOperAcount(curFa.getAccountId());
		cf.setChildId(childId);
		cf.setId(SQLUtils.generateId());
		ChildInfo childInfo = dao.saveChildFlower(cf);
		ctx.setSessionAttribute(KEY_Cur_Child, childId);
		ctx.json(JSONUtil.toJsonMsg(true, "成功", childInfo.toMap()));
	}

	private void jsonAdd() throws IOException {
		String name = ctx.getParameter("name");// 获取红花名称
		if (StringUtils.isEmpty(name)) {
			ctx.json(JSONUtil.toJsonMsg(false, "请输入一个有效的红花名称！"));
			return;
		}
		int type = SysFlower.ADD;
		try {
			type = Integer.parseInt(ctx.getParameter("type"));
			type = (type > 0) ? 1 : 0;
		} catch (Throwable e) {}
		FamilyFlower ff = new FamilyFlower();
		ff.setCreateDate(new Date());
		ff.setId(UserUtil.genUID());
		ff.setFamilyId(curFa.getFamilyId());
		ff.setName(name);
		ff.setOrder(dao.getMaxFamilyFlowerOrder(curFa.getFamilyId(), type) + 1);
		ff.setType(type);
		dao.createFamilyFlower(ff);
		ctx.json(JSONUtil.toJsonMsg(true, null, ff));
	}

	private void jsonChangeOrder() throws IOException {
		String flower1 = ctx.getParameter("flower1");//
		FamilyFlower f1 = dao.getFamilyFlower(flower1);
		if (f1 == null) {
			ctx.json(JSONUtil.toJsonMsg(false, "改变家庭红花的顺序时出错了！"));
			return;
		}
		String flower2 = ctx.getParameter("flower2");//
		FamilyFlower f2 = dao.getFamilyFlower(flower2);
		if (f2 == null) {
			ctx.json(JSONUtil.toJsonMsg(false, "改变家庭红花的顺序时出错了！"));
			return;
		}
		int order1 = 0;
		try {
			order1 = Integer.parseInt(ctx.getParameter("order1"));
		} catch (Throwable e) {}
		int order2 = 0;
		try {
			order2 = Integer.parseInt(ctx.getParameter("order2"));
		} catch (Throwable e) {}
		f1.setOrder(order1);
		f2.setOrder(order2);
		// System.out.println("f1.getName() = " + f1.getName() + " " + f1.getOrder() + " f2.getName() = " + f2.getName() + " " + f1.getOrder());
		dao.changeFamilyFlowerOrder(f1, f2);
		ctx.json(JSONUtil.toJsonMsg(true, null));
	}

	private void jsonDel() throws IOException {
		String flowerId = ctx.getParameter("id");//
		if (StringUtil.notEmpty(flowerId)) dao.deleteFamilyFlower(flowerId);
		ctx.json(JSONUtil.toJsonMsg(true, null));
	}

	private void gotoOverview() throws ServletException, IOException {
		ctx.forwardModule(UserService.Module, UserService.MD_OVERVIEW);// 跳转到总览页面
	}


	private void showNewsFlowers() {
		List<ChildFlower>  flowers=	ctx.getDao(FlowerDao.class).getNewsFlowers(this.curFa.getFamilyId());
		ctx.setRequestAttribute("flowers", flowers);
		ctx.forward("/WEB-INF/flower/flowerNews.jsp");// 小孩的红花明细列表
	}
	private void gotoFlowerDetail() throws ServletException, IOException {
		String childId = ctx.getParameter("childId");
		ChildInfo child = null;
		if (StringUtils.isEmpty(childId)) {
			gotoOverview();// 没有指明小孩信息，重新去总览页面选择小孩
			return;
		}
		child = ctx.getDao(UserDao.class).getFamilyChild(childId);
		if (child == null) {
			gotoOverview();// 查不到小孩信息，重新去总览页面选择小孩
			return;
		}
		int page = 1;
		String tmp = ctx.getParameter("_page");
		if (StringUtils.isNotEmpty(tmp)) {
			try {
				page = Integer.parseInt(tmp);
			} catch (Throwable e) {}
			if (StringUtils.isNotEmpty(tmp)) {// FIXME:从请求参数中取出查询条件
				String[] accounts = ctx.getRequest().getParameterValues("account");
				String[] flowerNames = ctx.getRequest().getParameterValues("flowerName");
				String startDate = ctx.getParameter("startDate");
				String endDate = ctx.getParameter("endDate");
			} else {// FIXME:从Session中取出查询条件

			}
		} else {// FIXME:从session中清理查询条件
		}
		int count = Page.PageCount;
		// count=5;
		tmp = ctx.getParameter("count");
		if (StringUtils.isNotEmpty(tmp)) try {
			count = Integer.parseInt(tmp);
		} catch (Throwable e) {}
		Page<ChildFlower> _page = dao.getChildFlowers(childId, (page - 1) * count + 1, count);
		ctx.setRequestAttribute("page", _page);
		ctx.setRequestAttribute("child", child);
		ctx.forward("/WEB-INF/flower/flowerDetail.jsp");// 小孩的红花明细列表
	}
}